<?php
/** 会员班级类
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\Db;
use think\facade\Session;

class TyMember extends \think\Model
{
    protected $table = 'sy_tk_member';
    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        $data = $this->where([['id', '=', $id]])->find();

        return $data;
    }

    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['title', '=', $name]])->find();
    }


    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'u.id desc'){
        $obj = $this->alias('u')
            ->field("cc.cate_title,u.*, m.user_name ")
            ->join("tk_cates cc", 'cc.id = u.cate', "LEFT")
            ->join("member m", 'm.id = u.uid', "LEFT")
            ->where('is_test',0)
            ->order($order_by);
        $result = get_page($obj, $condition, $page_size);
       
        return $result;
    }
    
    

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
        $title = trim($post['title']);
        $admin = $this->where([['title', '=', $title]])->find();
        if($admin){
            $this->error = '数据已存在';
            return false;
        }
        
        $data = $post;
        $time = time();
        $data['image'] = trim($data['image'], '|');
        $data['thumb'] = trim($data['thumb'], '|');
        $data['created'] = $time;
        $data['updated'] = $time;
        
        $model = new Lecturer;
        $lid = $post['lid'];
        $lid = explode(',', $lid);
        
        $lecturer = $model->_getListByWhere([['id', 'in', $lid]]);
        
        
        $lname = '';
        foreach($lecturer as $k=>$v){
            if(!empty($v['title'])){
                $lname .= $v['title'].'、';
            }
        }
        $lname = trim($lname, '、');
        $data['lname'] = $lname;
        
        if(!$this->insert($data)){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此数据';
            return false;
        }

        if(!$result->delete()){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }
    
    public function _openCourseAll($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此数据';
            return false;
        }

        $ret = $this->where(['id'=>$id])->update(['status'=>2]); 
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }
    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->delete();
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此数据';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '数据不存在';
            return false;
        }
        $data = $this->where([['title', '=', trim($post['title'])]])->find();
        //var_dump($data);die;
        if(!empty($data)){
            if($data->id != $result->id){
                $this->error = '数据已存在';
                return false;
            }
        }
        $post['image'] = trim($post['image'], '|');
        $post['thumb'] = trim($post['thumb'], '|');
        
        $model = new Lecturer;
        $lid = $post['lid'];
        $lid = explode(',', $lid);
        
        $lecturer = $model->_getListByWhere([['id', 'in', $lid]]);
        
        
        $lname = '';
        foreach($lecturer as $k=>$v){
            if(!empty($v['title'])){
                $lname .= $v['title'].'、';
            }
        }
        $lname = trim($lname, '、');
        $post['lname'] = $lname;
        
        foreach($post as $k=>$v){
            $result->$k = $v;
            
        }
        $result->updated = time();
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "停用成功";
            $error = "停用失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        return true;
    }


    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('u')
            ->join("member m", 'm.id = u.uid', "LEFT")
            ->where($where)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $type_id = isset($request['type_id']) ? $request['type_id'] : '';
        $title = isset($request['title']) ? $request['title'] : '';
        $user_name = isset($request['user_name']) ? $request['user_name'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['title'] = $title;
        $request['user_name'] = $user_name;
        $request['type_id'] = $type_id;
        
        $search = $request;
        
        
        
        
        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['title'])));
        $request['title'] = str_replace('%', "\%", $title);
        
        $request['start'] = empty($request['start']) ? '' : strtotime($request['start']);
        $request['end'] = empty($request['end']) ? '' : strtotime($request['end']);
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "u.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "u.created <= $end and ";
            }elseif($k == 'user_name'){
                $where .= "m.user_name like '%$v%' and ";
            }elseif($k == 'title'){
                $where .= "u.title like '%$v%' and ";
            }elseif($k == 'type_id'){
                $where .= "u.type_id = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }

    /**
     * 开通课程
     */
    public function _openQuestion($post){
        if(empty($post['id'])){
            $this->error = '';
            return false;
        }
        if(empty($post['uid'])){
            $this->error = '会员id缺失';
            return false;
        }

        $cid = (int)$post['id'];
        $mid = (int)$post['uid'];

        $cate_info = Question::get($cid);

        $effective_at = time()+$cate_info['effective_title']*30*24*60*60;


        $insert = ['cate'=>$cid, 'uid'=>$mid, 'effective_at'=>$effective_at,'create_at'=>time()];
        $where = ['cate'=>$cid, 'uid'=>$mid];
        $data = $this->where($where)->find();
        if(!empty($data)){
            $this->error = '该题库已开通';
            return false;
        }
        $this->startTrans();
        $insert['created_at'] = time();
        $ret = $this->save($insert);
        if(!$ret){
            $this->error = '开通失败';
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * 获取某用户的所有题库
     */
    public function _get_question_bank($condition = [], $page_size = PAGE_SIZE_API, $order_by = 'u.created desc'){
        $result = $this->alias('u')
            ->field("u.*,cc.cate_title")
            ->join("sy_tk_cates cc", 'cc.id = u.cate', "LEFT")
            ->order($order_by)
            ->where($condition)
            ->paginate();
        $result0 = $result->all();
        $uid     = $condition['u.uid'];
        foreach ($result0 as $k=>$v){
            $total_number         = Single::where('cate',$v['cate'])->count();
            $v['total_number']    = $total_number;
            $v['right_number']    = $this->_get_tk_right_number($v['cate'],$uid);
            $v['effective_at']    = date('Y-m-d H:i:s',$v['effective_at']);
            $result[$k] = $v;
        }
        return $result;
    }

    /**
     * 获取所购题库总题数
     */
     public function _get_all_number($mid){
         $cate_arr = $this->where('uid',$mid)->column('cate');
         if($cate_arr){
             $total_number = Single::where('cate','in',$cate_arr)->count();
         }else{
             $total_number = 0;
         }
        return $total_number;
    }

    /**
     * 获取某用户的所有题库
     */
    public function _get_question_detail($condition = []){
        $result = $this->alias('u')
            ->field("u.*,cc.cate_title")
            ->join("sy_tk_cates cc", 'cc.id = u.cate', "LEFT")
            ->where($condition)
            ->find();
        $result['effective_at'] = date('Y-m-d H:i:s',$result['effective_at']);
        return $result;
    }

    /**
     * 获取某用户的所有题库
     */
    public function _get_question_detail_two($condition = []){
        $result = Db::name('tk_cates')
            ->where($condition)
            ->find();
        $result['cate']         = $result['id'];
        $maps0['cate']         =   $result;
        $maps0['chapter_type'] = 1;
        $chapter_number = Db::name('tk_chapter_detail')->where($maps0)->count();

        $maps1['cate']         = $result;
        $maps1['chapter_type'] = ['gt',1];
        $test_number = Db::name('tk_chapter_detail')->where($maps1)->count();
        $result['chapter_number'] = $chapter_number;
        $result['test_number']    = $test_number;
        return $result;
    }

    /**
     * 获取正确率
     */
    public function _get_accuracy($uid){
        $total = Db::name('tk_record')->where('uid',$uid)->sum('total_number');
        $right = Db::name('tk_record')->where('uid',$uid)->sum('right_number');
        if(!$total){
            $total = 0;
        }
        if(!$right){
            $right = 0;
        }
        if($total==0 && $right==0){
            $back_percent = 0;
        }else {
            $back_percent = round($right / $total, 3) * 100;
        }
        $back_percent = $back_percent.'%';
        return $back_percent;
    }

    /**
     * 获取正确率
     */
    public function _get_right_number($uid){
        $right = Db::name('tk_record')->where('uid',$uid)->sum('right_number');
        if(!$right){
            $right = 0;
        }
        return $right;
    }

    /**
     * 获取整个题库正确率
     */
    public function _get_tk_right_number($cate,$uid){
        $detail_id_arr = Db::name('tk_chapter_detail')->where('cate',$cate)->column('id');

        $maps0[] = ['detail_id','in',$detail_id_arr];
        $maps0[] = ['uid','eq',$uid];
        $right = Db::name('tk_record')->where($maps0)->sum('right_number');
        if(!$right){
            $right = 0;
        }
        return $right;
    }
}